package com.jooink.sharewidget.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.Callback;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.ScriptInjector;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;

public class ShareWidgetFacebook implements IsWidget{

	private static boolean facebook_initialized=false;
	private static boolean facebook_failed=false;

	static {
		//G-plus script injection
		ScriptInjector.fromUrl("https://connect.facebook.net/en_US/all.js#xfbml=1").setCallback(
				new Callback<Void, Exception>() {
					@Override
					public void onSuccess(Void result) {
						facebook_initialized=true;
						vis_facebook_element();
					}
					@Override
					public void onFailure(Exception reason) {
						facebook_failed=true;
					}
				}
				).setWindow(ScriptInjector.TOP_WINDOW).inject();		

	}
	//G-plus static list
	static List<Element> facebook_list=new ArrayList<Element>();
	static List<FacebookOptions> facebook_opts=new ArrayList<FacebookOptions>();

	//G-plus repeating command
	static void vis_facebook_element() {
		for(int i=0;i<facebook_list.size();i++) {
			facebook_render(facebook_list.get(i),facebook_opts.get(i));
		}
		facebook_list.clear();
		facebook_opts.clear();
	};

	//Facebook Button
	public ShareWidgetFacebook(String href, String size, String annotation) {
		final FacebookOptions po=createOptions(href, size, annotation);
		facebook.addAttachHandler(new AttachEvent.Handler() {
			@Override
			public void onAttachOrDetach(AttachEvent event) {
				if(event.isAttached()) {
					render_facebook(po);
				}
			}
		});
	}

	private void render_facebook(FacebookOptions po) {
		if(facebook_failed)
			return;
		if(facebook_initialized) {
			facebook_render(facebook.getElement(),po);
		} else {
			facebook_list.add(facebook.getElement());
			facebook_opts.add(po);
		}
	}
	
	public static class FacebookOptions extends JavaScriptObject {
		protected FacebookOptions() {};
	}
	
	public native static FacebookOptions createOptions(String href, String size, String annotation) /*-{
		return {href:href,size:size,layout:annotation};
	}-*/;

	private static native void facebook_render(Element e, FacebookOptions po) /*-{
		var fblike = '<fb:like href="'+po.href+'" send="false" show_faces="false" layout="'+po.layout+'"></fb:like>'
   		//$('#fbdiv-'+data.id).append(fblike);
   		e.innerHTML=fblike;
   		$wnd.FB.XFBML.parse(e);
	}-*/;

	private HTML facebook=new HTML();

	@Override
	public Widget asWidget() {
		return facebook;
	}


}
